import qs from 'query-string';
import { postAdminLoginApi } from '../../api/auth';
import { LOGOUE_USERINFO_TYPE, UPDATE_USERINFO_TYPE } from './types';
import { commonLs, router, toLoginWithForm } from '../../utils/common';

const actions = {
  loginAdminAction: (params) => async (dispatch) => {
    try {
      const {
        adminname,
        token,
        checkedkeys,
        role,
      } = await postAdminLoginApi(params)
      dispatch({
        type: UPDATE_USERINFO_TYPE,
        payload:
        {
          adminname,
          token,
          checkedkeys,
          role,
        },
      })
      commonLs.put('adminname', adminname)
      commonLs.put('token', token)
      commonLs.put('checkedkeys', checkedkeys)
      commonLs.put('role', role)
      console.log(router)
      router.history.replace(qs.parse(router.history.location.search)?.from || '/')
    } catch (error) {
      console.log(error);
    }
  },
  logoutAdminAction: () => {
    commonLs.del('adminname')
    commonLs.del('token')
    commonLs.del('checkedkeys')
    commonLs.del('role')
    toLoginWithForm(router)
    return { type: LOGOUE_USERINFO_TYPE }
  },
}

export default actions
